package security

import (
	"boy-go/pkg/auth"
	"boy-go/pkg/constants"
	"boy-go/pkg/jwt"
	"boy-go/pkg/redis"
	"boy-go/pkg/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"net/http"
	"strings"
)

var (
	_loginUser  *auth.LoginUser
	_context    *gin.Context
	_permission *string
)

// VerifyToken 验证TOKEN
func VerifyToken(ctx *gin.Context) {
	_context = ctx
	token := ctx.GetHeader("Authorization")
	if token == "" {
		response.AjaxFail(ctx, http.StatusUnauthorized, "未登录")
		ctx.Abort()
		return
	}
	//前缀
	fix := "Bearer "
	//替换前缀
	token = strings.Replace(token, fix, "", 1)
	claims, err := jwt.ParseToken(token)
	if err != nil {
		if err.Error() == "token has invalid claims: token is expired" {
			response.AjaxFail(ctx, http.StatusUnauthorized, "TOKEN 已过期")
		} else {
			response.AjaxFail(ctx, http.StatusUnauthorized, "TOKEN ERR:"+err.Error())
		}
		fmt.Printf("%s", err)
		ctx.Abort()
		return
	}
	cacheStr := redis.GetValue(ctx, constants.LOGIN_TOKEN_KEY+claims.Uuid)
	if cacheStr == nil || *cacheStr == "" {
		response.AjaxFail(ctx, http.StatusUnauthorized, "未登录,TOKEN有误")
		ctx.Abort()
		return
	}
	err = json.Unmarshal([]byte(*cacheStr), &_loginUser)
	if err != nil {
		response.AjaxFail(ctx, http.StatusUnauthorized, "未登录,TOKEN有误:"+err.Error())
		ctx.Abort()
		return
	}
}

// GetLoginUser 获取登录用户
func GetLoginUser() *auth.LoginUser {
	return _loginUser
}

// GetLoginUserId 获取登录用户ID
func GetLoginUserId() *int64 {
	if _loginUser != nil {
		return &_loginUser.UserId
	}
	return nil
}

func SetPermission(permission string) {
	_permission = &permission
}

func GetPermission() *string {
	return _permission
}
